# Copyright (c) 2007 Fabio Makoto Akita
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Author: AkitaOnRails (www.akitaonrails.com)
# Support: Surgeworks LLC (www.surgeworks.com)

# Spawns a separated process to run the replication procedure. 
# everything goes logged and this log is accessed through an Ajax call
class Replicator
  include SyncsHelper::Tests # this will soon be deprecated
  include SyncsHelper::Actions
  include SyncsHelper::Handshake
  include SyncsHelper::Request
  include SyncsHelper::NetSupport
  include SyncsHelper::Misc

  # simulate a controller
  @@session, @@params = {}, {}

  def session; @@session; end
  def params;  @@params;  end
  def logger; RAILS_DEFAULT_LOGGER; end

  def run(logged_user = nil)
    puts "Logged In User: #{logged_user}"
    puts $SYNC_CONFIG.to_yaml
    # set the local user and run the sync procedure
    Replica.connection.reconnect! unless Replica.connection.active?
    Replica.load_config
    begin
      # has to pass @logged_user before the load command in the runner script
      session[:user] = logged_user
      User.current_user = User.find(logged_user)
      run_sync
    rescue => e
      puts "Problems with User. Did you pass it properly?"
      puts e.to_yaml
    end
    exit!
  end
end

Replicator.new.run(@logged_user)